<template>
	<view>
		<u-popup v-model="classStore.Pop" mode="bottom" height="900rpx">
			<view style="margin: 15rpx;">
				<u-form :model="form" ref="form1">
					<u-form-item label="类型">
						<u-input v-model="form.type.label" placeholder="选择课程种类" type="select" @click="showLessonType=true" />
					</u-form-item>
					<u-form-item label="学科">
						<u-input v-model="form.subjectId" placeholder="预约学科" type="select" @click="showSelectSubject=true" />
					</u-form-item>
					<u-form-item label="日期">
						<u-input v-model="form.date" placeholder="选择日期" @click="canshowDate()" />
					</u-form-item>
					<u-form-item label="时间">
						<u-input v-model="form.time" placeholder="选择时间" @click="canshowTime()" /> 
					</u-form-item>
				</u-form>
		
				<button @click="submitLess">提交</button>
				<view style="font-size: var(--text-12); color: #777; width: 100%; text-align:center; line-height: 30px;">不能选择的时间段说明该时间段已被占用</view>
				<view style="font-size: var(--text-12); color:#777; text-align: center; line-height: 30px;">
					<text>最佳复习时间:</text>
					<text v-for="(item,index) in wpList">
						{{item.title}}:{{item.count}}个
					</text> 
				</view> 
				<view style="font-size: var(--text-12); color:#777; text-align: center; line-height: 30px;">
					<view>
						<text v-if="reviewfirst" style="color:#000;font-size:var(--text-14);">系统建议优先复习,</text>
						<text v-else="reviewfirst" style="color:#000;font-size:var(--text-14);">系统建议优先学新,</text>
						<text>请根据具体情况预约下一节课</text>
					</view> 
				</view> 
			</view>
		</u-popup>
		<u-popup v-model="classStore.CancelLes" mode="bottom" height="300rpx" z-index="998">
			<view style="margin: 15rpx;">
				<u-form>
					<u-form-item label="原因">
						<u-input v-model="cancelRes" type="textarea" border height="100" auto-height />
					</u-form-item>
				</u-form>
		
				<button @click="confirmcancel">提交</button>
			</view>
		</u-popup>
		<u-select v-model="showLessonType" :list="classStore.LessonType" @confirm="selectType"></u-select>
		<u-select v-model="showSelectSubject" :list="classStore.SubjectList" @confirm="selectSubject"></u-select>
		<u-calendar v-model="showDate" :max-date="classStore.maxDate" :min-date="classStore.minDate" mode="date" @change="confirmDate"></u-calendar> 
		<u-select v-model="showTime" mode="mutil-column-auto" :list="timelist" label-name="label" value-name="value" child-name="children" @confirm="confirmTime"></u-select>
	</view>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue';
	import { useClassStore } from '@/store/class';
	import { ktlapi, ktluser, pivotJson } from '@/utils';
	import { onShow } from '@dcloudio/uni-app';
	
	/** 扩展内容：学生 */
	defineOptions({ name: 'class-student-expand', inheritAttrs: false });
	
	const props = defineProps(['stid','wplist'])
	
	const classStore = useClassStore();
	
	const cancelRes = ref('');
	const showLessonType = ref(false);
	const showSelectSubject = ref(false);
	const showDate = ref(false);
	const showTime = ref(false);
	const timelist = ref([]);
	const form = ref<any>({
		"type": {},
		"subjectId": "",
		"date": "",
		"time": ""
	}) 
	
	function selectType(res: any[]) {
		console.log('selectType', res[0]);
		form.value.type = res[0];
	}
	function selectSubject(res: any[]) {
		console.log('selectSubject', res[0]);
		form.value.subjectId = res[0];
	}
	
	function canshowDate(){ 
		//console.log(props.stid || ktluser.BaseInfo().AccountID);
		if(form.value.type.value){
			showDate.value=true;
		}else{
			uni.showToast({
				title:"未选择类型",
				icon: "error",
				duration: 2000
			})
		}
	}
	
	function canshowTime(){
		if(form.value.date != ""){
			showTime.value=true
		}else{
			uni.showToast({
				title:"未选择日期",
				icon: "error",
				duration: 2000
			})
		}
		
	}
	
	function submitLess() {
		if(form.value.time == ""){
			return;
		}
		uni.showLoading({
			title: '提交中'
		});
		ktlapi({
			action: "Cus_StudentPerLes",
			data: {
				"StudentAccountId": props.stid || ktluser.BaseInfo().AccountID,
				"StudyDay": form.value.date,
				"StartTime": form.value.time,
				"LessonType": form.value.type.value
			}
		}).then((res: any) => {
			uni.hideLoading();
			if (res.data[0]["code"] == 1) {
				form.value = {
					"type": {},
					"date": "",
					"time": ""
				};
				classStore.loadLessons();
				classStore.setPop(false);
				uni.showToast({
					title: res.data[0]["msg"],
					icon: "success",
					duration: 2000
				});
			} else {
				uni.showToast({
					title: res.data[0]["msg"],
					icon: "error",
					duration: 2000
				});
			}
		});
	}
	
	const reviewfirst = ref(false);
	const wpList = ref([{
		"title": "已过期",
		"tp": 0,
		"count": 0
	},
	{
		"title": "24小时内",
		"tp": 1,
		"count": 0
	}, {
		"title": "更长时间",
		"tp": 2,
		"count": 0
	}]);
	
	onShow(() => {  
		if(props.wplist){
			wpList.value = props.wplist;
			if(wpList.value[0]["count"] + wpList.value[1]["count"] >= 30){
				reviewfirst.value = true;
			} 
		}else{
			ktlapi({
				action: "STUTimeComm",
				data: {
					StudentAccountId: props.stid || ktluser.BaseInfo().AccountID
				}
			}).then((data : any) => {
				for(var i=0;i<wpList.value.length;i++){ 
					for(var j=0;j<data.data.length;j++){
						if(wpList.value[i]["tp"] == data.data[j]["TP"]){
							wpList.value[i]["count"] = data.data[j]["Cnt"]
							break;
						}
					}
				}  
				if(wpList.value[0]["count"] + wpList.value[1]["count"] >= 30){
					reviewfirst.value = true;
				} 
			});
		}
	});
	
	function confirmcancel() {
		if (cancelRes.value == '') {
			uni.showToast({
				title: '未输入',
				icon: "error",
				duration: 2000
			});
			return;
		}
		uni.showModal({
			title: '提示',
			content: '是否确认取消该课程?',
			success: function(res) {
				if (res.confirm) {
					uni.showLoading({
						title: '提交中'
					});
					ktlapi({
						action: "Cus_CancelLess",
						data: {
							"ID": classStore.activeItem.ID,
							"Detail": cancelRes.value,
						}
					}).then(res => {
						classStore.setCancelLes(false);
						classStore.activeItem.Status = 3;
						classStore.activeItem.StatusTitle = '已取消';
						uni.hideLoading();
					});
	
				} else if (res.cancel) {}
			}
		});
	}
	
	function confirmDate(dateRes: any) {
		
		console.log(dateRes);
		form.value.date = dateRes.result;
		timelist.value = [];
		var allTime = [];
		
		uni.showLoading({
			title: '加载中'
		});
		ktlapi({
			action: "Cus_LesstimesByStudent",
			data: {
				"StudentAccountId": props.stid ||  ktluser.BaseInfo().AccountID,
				"StudyDay": form.value.date,
			}
		}).then((res: any) => {
			uni.hideLoading(); 
			
			// 获取到选择的日期内已经预约的时间区间数据
			var ExistLess = res.data;
			// console.log(ExistLess);
			
			// 可选起始时间提前 1:05
			const perStart = form.value.type.value == 2 ? 19 : 104;
			// 可选结束时间延后 0:04
			const lstEnd = 4; 
			
			// 约课范围：AM 8:00 - PM 22:00
			// 约课周期：1h(正课)/
			// 结合数据结构，采用 100 进制更好组织数据结构
			for (let i = 800; i <= 2200; i++) {
				
				if (dateRes.isToday) {
					const hour = new Date().getHours().toString().padStart(2, '0');
					const minute = new Date().getMinutes().toString().padStart(2, '0')
					// 如果是当天预约，至少提前2小时预约
					if (Number.parseInt(hour + minute) + 200 > i) {
						continue;
					}
				}
				
				// 是否可以使用：对约课范围内的所有时分进行筛选，若已经被预约，则不能使用
				let canuse = true;
				for (let j = 0; j < ExistLess.length; j++) {
					// 开始的时分(100进制)
					const StartTime = Number.parseInt(ExistLess[j].StartTime || 0);
					// 结束的时分(100进制)
					const EndTime = Number.parseInt(ExistLess[j].EndTime || 0);
					
					// 对100进制开始时分进行矫正 1205 - 19 = 1186
					let k = StartTime - perStart;
					if (k % 100 >= 60) {
						const startHour = k.toString().padStart(4, '0').substring(0, 2);
						const startMinute = 60 - (100 - k % 100);
						k = Number.parseInt(startHour + startMinute.toString().padStart(2, '0'));
					}
					
					// 若结束时分延后4分钟超过1小时，例如：859 + 4 = 863
					const condition = EndTime + (EndTime % 100 + lstEnd >= 60 ? lstEnd + 40 : lstEnd);
					for (; k <= condition; k++) {
						if (k == i) {
							canuse = false;
						}
					}
				}
				
				// 此时分可以使用，则添加进可选数据结构
				if (canuse) {
					// 945 => 0945
					const minuteStr = i.toString().slice(-2);
					const hourStr = i.toString().substring(0, i.toString().length - 2);
					hourStr.padStart(2, '0');
					
					if (Number.parseInt(minuteStr) >= 60) {
						continue;
					}
					allTime.push({ "Hour":hourStr, "Minute": minuteStr })
				}
			}
			 
			var temp = pivotJson(allTime,"Hour",["Hour","Minute"]);
			// console.log('temp', temp)
			for(var i=0;i<temp.length;i++){
				var item = {
					"value":temp[i]["data"]["Hour"],
					"label":temp[i]["data"]["Hour"],
					"children":[],
				};
				for(var j=0;j<temp[i]["items"].length;j++){
					item.children.push(
					{
						"value":temp[i]["items"][j]["Minute"],
						"label":temp[i]["items"][j]["Minute"]
					});
				}
				timelist.value.push(item);
			} 
			console.log('timelist.value', timelist.value)
		}); 
	}
	function confirmTime(res: any) {
		console.log(res);
		form.value.time = res[0].label + ':' + res[1].label;
	}
	
	watch(
		() => classStore.CancelLes, 
		(nVal: boolean) => {
			if(nVal) {
				cancelRes.value = '';
			}
		}
	)
</script>

<style lang="scss">
</style>